﻿<template>
	<el-dialog v-model="state.isShowDialog" fullscreen lock-scroll :show-close="false" :modal="false" draggable=""
		:close-on-click-modal="false" class="Admin-full-dialog">
		<div class="Admin-full-dialog-header">
			<div class="header-title">
				<img :src="themeConfig.logoUrl" class="header-logo" />
				<p class="header-txt"> · 打印模板</p>
			</div>
			<el-steps :active="state.activeStep" finish-status="success" simple class="steps steps2" v-if="!state.loading">
				<el-step title="基础设置" @click.native="stepChick(0)" />
				<el-step title="打印设计" @click.native="stepChick(1)" />
			</el-steps>
			<div class="options">
				<el-button @click="prev" :disabled="state.activeStep <= 0">{{ $t('message.common.prev') }}</el-button>
				<el-button @click="next" :disabled="state.activeStep >= 1 || state.loading" :loading="state.nextBtnLoading">
					{{ $t('message.common.next') }}
				</el-button>
				<el-button type="primary" @click="submit" :disabled="state.activeStep != 1" :loading="state.btnLoading">{{
					$t('message.common.saveButton') }}</el-button>
				<el-button @click="cancel">{{ $t('message.common.cancelButton') }}</el-button>
			</div>
		</div>
		<div class="main" v-loading="state.loading">
			<el-row type="flex" justify="center" align="middle" v-if="!state.activeStep" class="basic-box">
				<el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="10" class="basicForm">
					<el-form :model="state.ruleForm" :rules="rules" ref="ruleFormRef" label-width="auto">
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="模板名称" prop="name">
									<el-input v-model="state.ruleForm.name" placeholder="模板名称" maxlength="160" show-word-limit clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="数据状态" prop="enabledMark">
									<el-radio-group v-model="state.ruleForm.enabledMark">
										<el-radio :value="1">启用</el-radio>
										<el-radio :value="2">禁用</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="模板说明" prop="remark">
									<el-input v-model="state.ruleForm.remark" placeholder="模板说明" type="textarea" :rows="3" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-alert title="默认打印的时候必须传业务主键@formId给SQL语句里面作为Where查询条件" type="warning" show-icon :closable="false">
								</el-alert>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="数据连接" prop="dbLinkId">
									<el-select v-model="state.ruleForm.dbLinkId" placeholder="请选择数据库" clearable filterable>
										<el-option-group v-for="group in state.dbLinkOptions" :key="group.name" :label="group.name">
											<el-option v-for="item in group.children" :key="item.id" :label="item.name" :value="item.id" />
										</el-option-group>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
								<el-form-item label="SQL语句" prop="sqlTemplate">
									<el-row :gutter="10" style="width: 100%;" class="mb20">
										<el-button icon="ele-Plus" type="primary" plain @click="handleAddSql"> 新增SQL </el-button>
									</el-row>
									<el-row :gutter="10" v-for="(v, k) in state.sqlTemplate" :key="k" style="width: 100%;">
										<el-col :xs="24" :sm="20" :md="20" :lg="20" :xl="20" class="mb20">
											<el-input v-model="v.sql" placeholder="请输入SQL查询语句&存储过程语句" type="textarea"
												:autosize="{ minRows: 3, maxRows: 10 }" clearable />
										</el-col>
										<el-col :xs="24" :sm="3" :md="3" :lg="3" :xl="3" class="mb20">
											<el-button icon="ele-Delete" type="danger" circle plain size="small" @click="handleDelSql(k)" />
										</el-col>
									</el-row>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-col>
			</el-row>
			<template v-if="state.activeStep == 1">
				<HiprintDesign ref="hiprintDesignRef" v-if="state.activeStep == 1 && state.showPrintDesign"
					:treeData="state.treeData" v-model:value="state.ruleForm.printTemplate" @input="onDesignChange" />
			</template>
		</div>
	</el-dialog>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { addPrintDev, updatePrintDev, detailPrintDev, getFields } from "/@/api/system/printDev";
import { selectorSysDbLink } from "/@/api/system/sysDbLink";
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import HiprintDesign from '/@/views/system/printDev/component/hiprint/index.vue';
import { formatDate } from '/@/utils/formatTime';

const hiprintDesignRef = ref<InstanceType<typeof HiprintDesign>>();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: "",
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const ruleFormRef = ref();
const state = reactive({
	activeStep: 0,
	loading: false,
	nextBtnLoading: false,
	btnLoading: false,
	isShowDialog: false,
	showPrintDesign: false,
	ruleForm: {
		id: undefined,
		name: '',
		enabledMark: 1,
		sqlTemplate: '',
		dbLinkId: '0',
		printTemplate: '',
		parameterJson: '',
		remark: '',
	},
	parameterJson: [],
	sqlTemplate: [] as any,
	dbLinkOptions: [] as any,
	treeData: [],
});

//自行添加其他规则
const rules = ref<FormRules>({
	name: [
		{ required: true, message: '模板名称不能为空', trigger: 'blur' },
	],
	dbLinkId: [
		{ required: true, message: '数据连接不能为空', trigger: 'change' },
	],
	sqlTemplate: [
		{ required: true, message: 'SQL语句不能为空', trigger: 'click' },
	],
});

// 页面加载时
onMounted(() => {

});

// 打开弹窗
const openDialog = async (row: any) => {
	getDataSource();
	state.sqlTemplate = [];
	state.activeStep = 0;
	state.parameterJson = [];
	state.treeData = [];
	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id) {
		state.ruleForm = (await detailPrintDev(rowData.id)).data.result;
		state.ruleForm.dbLinkId = state.ruleForm.dbLinkId + '';
		state.parameterJson = state.ruleForm.parameterJson && JSON.parse(state.ruleForm.parameterJson) || [];
		state.sqlTemplate = state.ruleForm.sqlTemplate && JSON.parse(state.ruleForm.sqlTemplate) || []
	}
	state.isShowDialog = true;
	state.showPrintDesign = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.isShowDialog = false;
	state.showPrintDesign = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
	state.showPrintDesign = false;
};

function prev() {
	state.activeStep -= 1
}

function next() {
	if (state.activeStep < 1) {
		const values = validate();
		if (!values) return;
		state.ruleForm = { ...state.ruleForm, sqlTemplate: JSON.stringify(state.sqlTemplate), parameterJson: JSON.stringify(state.parameterJson) };
		if (!exist()) return;
		state.nextBtnLoading = true;
		const query = {
			dbLinkId: state.ruleForm.dbLinkId,
			sqlTemplate: state.ruleForm.sqlTemplate,
		};
		getFields(query)
			.then(res => {
				state.treeData = res.data.result;
				state.activeStep += 1;
				state.nextBtnLoading = false;
			})
			.catch(() => {
				state.nextBtnLoading = false;
			});
	}
}

function stepChick(key: any) {
	if (state.activeStep <= key) return
	state.activeStep = key
}

function handleAddSql() {
	state.sqlTemplate.push({ sql: '' });
}

function handleDelSql(i: Number) {
	state.sqlTemplate.splice(i, 1);
}

function onDesignChange(val: any) {
	state.ruleForm.printTemplate = val;
}

function exist() {
	if (!state.sqlTemplate.length) {
		ElMessage.error('请输入SQL语句');
		return false;
	}
	let isOk = true;
	for (let i = 0; i < state.sqlTemplate.length; i++) {
		const e = state.sqlTemplate[i];
		if (!e.sql) {
			ElMessage.error(`第${i + 1}行SQL语句不能为空`);
			isOk = false;
			break;
		}
	}
	return isOk;
}

function validate() {
	let isOk = true;
	ruleFormRef.value.validate(async (valid: boolean) => {
		if (valid) isOk = true;
		else isOk = false;
	});
	return isOk;
}

function getDataSource() {
	selectorSysDbLink({}).then((res: any) => {
		let list = res.data.result.list || [];
		list = list.filter((o: any) => o.children && o.children.length);
		state.dbLinkOptions = list;
	});
}


// 提交
const submit = async () => {
	let values = state.ruleForm;
	if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
		await addPrintDev(values);
	} else {
		await updatePrintDev(values);
	}
	closeDialog();
};






//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
